import 'dart:async';

import 'package:fate_blind_box/network/Api.dart';
import 'package:fate_blind_box/routes/page_route_names.dart';
import 'package:fate_blind_box/utils/loading.dart';
import 'package:fate_blind_box/utils/snack_bar.dart';
import 'package:get/get.dart';

import 'state.dart';

class SmsVerifyLogic extends GetxController {
  final SmsVerifyState state = SmsVerifyState();

  /// 发送短信验证码
  sendVerifyCode() {
    if (state.mobController.text.length < 11) {
      toast("请输入手机号");
      return false;
    }
    loading(() async {
      final res =
          await Api.getInstance().loginSendCode(state.mobController.text);
      if (res['code'] == 0) {
        if (res['data'] != null && res['data']['sig'] != null) {
          state.smsSig = res['data']['sig'];
          _startCountdownTimer();
        }
      } else {
        ThemeSnackBar.show(Get.context!, res['msg']);
      }
    });
  }

  ///开始倒计时
  _startCountdownTimer() {
    state.curTime.value = 60;
    state.timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      state.curTime.value--;
      if (state.curTime.value <= 0) {
        state.timer?.cancel();
      }
    });
  }

  /// 提交验证码
  submitAction() {
    if (state.codeController.text.length < 4) {
      toast("请输入验证码");
      return;
    }
    if (state.mobController.text.length < 11) {
      toast("请输正确的手机号");
    }
    loading(() async {
      final res = await Api.getInstance().verifySms(state.mobController.text,
          state.codeController.text, state.smsSig, "LOGIN");
      if (res['code'] == 0) {
        toast("验证成功");
        Get.offAndToNamed(PageRouteNames.setPaymentPassword);
      }
      toast(res['msg']);
    });
  }
}
